import { _decorator, Color, Component, director, instantiate, Node, Prefab, Sprite, SpriteFrame, sys, UI, UITransform, Vec2, Vec3 } from 'cc';
import Net from '../frame/managers/NetMgr';
import configs from '../Configs';
import oh, { ohPages } from './OhCtrl';
import { RectCtrl } from './RectCtrl';
import { RoomData } from '../deco/RoomBuilder';
import { RoomViewCtrl } from './RoomViewCtrl';
import { aa } from '../frame/FrameCore';
import { ui } from '../frame/common/Enums';
import HIT, { HitCtrl } from './HitCtrl';
import { BuildCtrl } from '../deco/BuildCtrl';
import { Player } from '../Phyic/Player';
const { ccclass, property } = _decorator;

const normal = new Color(175, 175, 185, 255);
const pressed = Color.WHITE;
const bigRectPos = 1;
const smallRectPos = -152;
const maxHeight = 660;
@ccclass('testObj')
class testObj{
    @property scale = 0.3;
    @property(SpriteFrame) sp:SpriteFrame;
    @property(Prefab) model:SpriteFrame;
}

@ccclass('DecoCtrl')
export class DecoCtrl extends Component {
    @property(Sprite)
    btnSP: Sprite[] = []
    @property(Node)
    plate: Node = null;
    @property(testObj) testObjs:[] = []

    @property(Node)
    defaultFuns: Node[] = []
    @property(SpriteFrame)
    testSP: SpriteFrame = null;
    @property(Prefab)
    smallRect: Prefab = null;
    @property(Prefab)
    bigRect: Prefab = null;

    @property(Node)
    roomPlate: Node = null;
    @property(UITransform)
    views: UITransform[] = []
    _currentIndex = -1;
    smalls: Node[] = [];
    bigs: Node[] = [];
    funList: Function[] = [this.showBigRects.bind(this), this.showSmallRects.bind(this), this.showFoot.bind(this)];
    static ins: DecoCtrl;
    private rooms: RoomViewCtrl[] = []

    onEnable() {
        DecoCtrl.ins = this;
        //for default
        BuildCtrl.ins.testJsonBuild();


        HIT.addTest(aa.res.get('testFurniture',director.getScene()))

        this.addTestObj();
      
        this.testObjs.forEach((obj)=>{
            const rect = this.newSmallRect();
            rect.setObj(obj)

        })
        const big = instantiate(this.bigRect);
        const bigRect = big.getComponent(RectCtrl);
        bigRect.setSP(this.testSP)
        this.bigs.push(big);
        bigRect.callback = () => {
            BuildCtrl.ins.testJsonBuild()
        }
        this.btnSP.forEach((btn, i) => {
            btn.node.parent.on(Node.EventType.TOUCH_END, () => {
                this.views[2].node.setPosition(0, 0);
                this.setPressed(i)
            }, this)

        })
        this.setPressed(1);
        this._currentIndex == 1;
        director.on("RoomSelect", this.setRoomPress, this);


    }
    addTestObj(){
          const small = instantiate(this.smallRect);
        const smallRect = small.getComponent(RectCtrl);
        smallRect.glb = 'http://iwae.oss-cn-beijing.aliyuncs.com/20250608_115110.glb'
        smallRect.setSpFromBase64(configs.testBase64, "064b4841-b5a0-4f08-ac35-e14d9fbe63a5")
        this.smalls.push(small);

    }
    setRoomPress(index: number) {
        this.rooms.forEach((room, i) => {
            room.press = (index == i) ? true : false;
        })

    }

    addBig(base64: string) {
        const bigRect = this.newBigRect();
        bigRect.setSpFromBase64(base64)

    }
    newBigRect() {
        const big = instantiate(this.bigRect);
        this.bigs.push(big);
        const row = this.bigs.length + 1;
        big.setPosition(bigRectPos, -177 * row + 177)
        this.views[2].node.addChild(big);
        const bigRect = big.getComponent(RectCtrl);

        this.views.forEach((view, i) => {
            let height = 178 * row

            if (i <= 1) {
                height = Math.min(height, maxHeight)
            }
            view.setContentSize(240, height)
        })
        return bigRect
    }
    addSmallFromBase64(base64) {
        const smallRect = this.newSmallRect();
        smallRect.scale = 0.52;
        smallRect.setSpFromBase64(base64)
    }
    newSmallRect() {
        const s = instantiate(this.smallRect);
        const index = this.smalls.length + 1;
        const row = Math.floor(index / 2);
        const col = index % 2;
        s.setPosition(smallRectPos + 150 * col, row * -150, 0);
        this.views[2].node.addChild(s);
        const smallRect = s.getComponent(RectCtrl);
        this.smalls.push(s);

        this.views.forEach((view, i) => {
            let height = 152 * row + 152

            if (i <= 1) {
                height = Math.min(height, maxHeight)
            }
            view.setContentSize(320, height)
        })
        return smallRect;
    }
    clear() {
        const children = this.roomPlate.children.slice(); // 创建副本
        this.roomPlate.removeAllChildren();

        // 然后回收到资源池
        children.forEach(child => {
            aa.res.put(child);
        });
        this.rooms.length = 0;
    }

    initRoomData(rooms: RoomData[]) {

        rooms.forEach((room, index) => {
            this.addRoom(room.name, room.size * 0.4, room.position, index + 1)
        })


    }
    addRoom(name: string, width: number, position: { x: number, y: number }, index: number): RoomViewCtrl {
        const roomNode = aa.res.get("RoomSelectView");
        const roomView = roomNode.getComponent(RoomViewCtrl)
        roomView.init(name, width, position, index);
        this.roomPlate.addChild(roomNode);
        this.rooms.push(roomView);
        return roomView;
    }



    async generateFromPrompt(prompt: string, type = -1) {
        const smallRect = this.newSmallRect();
        smallRect.setSpFromPrompt(prompt, type)

    }

    setPressed(index: number) {
        console.log("pressed" + index)
        const y = (1 - index) * 196;
        this.plate.setPosition(0, y, 0);
        const funC = this.funList[index];
        funC && funC();
        this.btnSP.forEach((btn, i) => {
            btn.color = (index == i) ? pressed : normal;
            this.defaultFuns[i] && (this.defaultFuns[i].active = (index == i));
        })
        this._currentIndex = index;
    }
    putSmall() {
        this.smalls.forEach(s => {
            s.removeFromParent();
        })
    }
    putBig() {
        this.bigs.forEach(s => {
            s.removeFromParent();
        })


    }
    async showFoot() {
        if(this._currentIndex ==2) return
        this.putBig()
        this.putSmall()
         this.views.forEach((view, i) => {
            
            view.setContentSize(0, 0)
        })
        HIT.clearClick();
        
        aa.ui.put(ui.ChatView)
        await aa.ui.get(ui.Joystick)
        aa.global.playerNode = aa.res.get("player",director.getScene());
        const player = aa.global.playerNode.getComponent(Player);
        player.init();
        aa.global.isGame = true;
        const cam = aa.global.orbitCam;
        cam.target = player.target;
        cam.resetGame();
        this.setRoomPress(1);

    }
    backBuild() {
        aa.global.isGame = false;
        aa.global.orbitCam.target = aa.global.orbitCam.orbitTarget.node;
        aa.res.put(aa.global.playerNode)
        aa.ui.get(ui.ChatView);
        aa.ui.put(ui.Joystick);
        this.rooms[0].onClick();
    }

    showSmallRects() {
        if (this._currentIndex == 0) this.putBig()
        if (this._currentIndex == 2) this.backBuild()

        this.smalls.forEach((s, i) => {
            s.parent = this.views[2].node;
            const index = i + 1;
            const row = Math.floor(index / 2);
            const col = index % 2;
            s.setPosition(smallRectPos + 150 * col, row * -150, 0);
        })
        const index = this.smalls.length + 1;
        const row = Math.floor(index / 2);

        this.views.forEach((view, i) => {
            let height = 152 * row + 152;

            if (i <= 1) {
                height = Math.min(height, maxHeight)
            }
            view.setContentSize(320, height)
        })

    }

    showBigRects() {
        if (this._currentIndex == 1) this.putSmall()
        if (this._currentIndex == 2) this.backBuild()

        this.bigs.forEach((b, i) => {
            b.parent = this.views[2].node;
            b.setPosition(bigRectPos, -177 * (i + 1), 0);
        })
        const row = this.bigs.length + 1;

        this.views.forEach((view, i) => {
            let height = 178 * row

            if (i <= 1) {
                height = Math.min(height, maxHeight)
            }
            view.setContentSize(240, height)
        })


    }
    async cameraFunc() {
        if (sys.platform === sys.Platform.OPENHARMONY) {
            oh.openPage(ohPages.CameraPage);

        } else {
            const res = await Net.sendRequest(configs.serverUrl, { base64: configs.testBase64 })
            console.log("cocos res", res)
        }
    }
    async scanFunc() {
        if (sys.platform === sys.Platform.OPENHARMONY) {
            oh.openPage(ohPages.DocPage);
        }
    }


}

